package com.tarena.lbs.activity.exception;

import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessExceprion(BusinessException e) {
        log.error("BusinessException: code={}, msg={}", e.getCode(), e.getMessage());
        return  Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理请求体参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));

        log.error("MethodArgumentNotValidException: {}", errorMessage);
        return Result.fail("400", errorMessage);
    }

    /**
     * 处理请求参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.joining(", "));

        log.error("BindException: {}", errorMessage);
        return Result.fail("400", errorMessage);
    }
    }